package cn.janescott.file.server.dao;

import cn.janescott.file.server.FileServerStarter;
import cn.janescott.file.server.dto.FileInfoDTO;
import cn.janescott.file.server.exception.MyException;
import cn.janescott.file.server.exception.MyExceptionEnums;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.*;

/**
 * 文件存储
 *
 * @author scott
 * @date 2019/4/15
 */
public class FileDao {

    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 文件信息保存
     *
     * @param info
     */
    public void save(FileInfoDTO info) {
        try {
            Connection connect = getConnect();
            String sql = "insert into file_info " +
                    "(file_name, file_path, content_type, uploader)" +
                    "values" +
                    "(?, ?, ?, ?)";
            PreparedStatement prep = connect.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            prep.setString(1, info.getName());
            prep.setString(2, info.getPath());
            prep.setString(3, info.getContentType());
            prep.setString(4, info.getUploader());

            prep.execute();
            ResultSet resultSet = prep.getGeneratedKeys();
            while (resultSet.next()) {
                info.setId(resultSet.getLong(1));
            }
            connect.commit();
            connect.close();
        } catch (SQLException se) {
            logger.error(se.getMessage(), se);
            throw MyException.failed(MyExceptionEnums.DATABASE_EXCEPTION, se);
        }
    }


    /**
     * 获取连接
     *
     * @return
     * @throws SQLException
     */
    private Connection getConnect() throws SQLException {
        return ((DataSource) FileServerStarter.get(DataSource.class)).getConnection();
    }

}
